import React, { Component } from 'react'
import { connect } from 'react-redux'
import InfiniteScroll from 'react-infinite-scroller'
import CourseList from './CourseList'
import { withStyles } from 'material-ui/styles'

const styles = theme => ({
	loader: {
		width: '100%',
		textAlign: 'center',
		paddingTop: 20,
		color: 'green',
		paddingBottom: 1000
	},
	emptyPage: {
		minHeight: 500,
		color: 'green',

	}
})
@connect(mapStateToProps)
@withStyles(styles)
class CourseListScroll extends Component {
	constructor(props) {
	  super(props)
	}

	async loadItems() {
		const res = await this.props.fetchCourse(this.props.searchKey);
		this.props.setCourse(res.data.courses)
		this.props.setPagination(res.data)
	}

	getEmptyPage() {
		const {classes} = this.props
		return (
			<div className={classes.emptyPage}>
				没有搜到相关课程， 后续考虑增加，感谢您的使用.
			</div>
		)
	}

	render() {
  	const {classes, courses, hasNext} = this.props
  	const loader = <div className={classes.loader}>课程加载中 ...</div>
		return (
      	courses.length !== 0 ?
      		<InfiniteScroll
		        pageStart={0}
		        loadMore={this.loadItems.bind(this)}
		        hasMore={hasNext}
		        loader={loader}
		        initialLoad={false}
		        >
		        <CourseList {...this.props} />
		      </InfiniteScroll>
				:
				this.getEmptyPage()
		)
	}
}

function mapStateToProps( state ) {
	return {
		courses: state.courses,
		searchKey: state.searchKey,
		hasNext: state.paginator.hasNext,
		isAuthed: state.auth.isAuthed
	}
}

export default CourseListScroll
